﻿using System;
using System.Collections.Generic;
using System.ServiceModel;

using NetStsAdm.NetStsAdmService;

namespace NetStsAdm
{
    internal class Command
    {
        Dictionary<string, string> keyValues;
        ICommand command;
        Config cfg;

        #region Static members

        internal static Dictionary<string, string> ParseArgs(string[] args)
        {
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            
            for (int i = 0; i < args.Length; i++)
            {
                string k = "", v = "";
                if (args[i].StartsWith("-"))
                {
                    k = args[i].ToLower();
                    if (i < args.Length - 1 && !args[i + 1].StartsWith("-"))
                    {
                        v = args[i + 1];
                        i = i + 1;
                    }
                }
                keyValues.Add(k, v);
            }
            return keyValues;
        }

        #endregion

        internal Command(Dictionary<string, string> args)
        {
            keyValues = args;

            // Construct the Command to execute, i.e. get the correct type
            BuiltInCommands commands = new BuiltInCommands();
            Type cmdType = commands.GetCommandType(keyValues.Keys) as Type;
            if (cmdType == null)
                throw new ArgumentException();

            command = Activator.CreateInstance(cmdType) as ICommand;

            // Call the singleton so that stuff are created if they don't exist
            cfg = Config.GetConfig();            
        }

        /// <summary>
        /// Execute the specified command
        /// </summary>
        /// <returns>
        ///  0 : success
        /// -1 : General error (other than syntax)
        /// -2 : syntax error
        /// </returns>
        internal int Execute(out string Output)
        {
            try
            {
                return command.Execute(keyValues, out Output);
            }
            catch (Exception ex)
            {
                Output = ex.Message;
                return -1;
            }
        }
    }
}